package com.cookbook.controller;

import com.cookbook.Result;
import com.cookbook.database.model.User;
import com.cookbook.entity.Token;
import com.cookbook.service.UserService;
import com.cookbook.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author 毛川
 */
@Controller
@RequestMapping("/authentication")
public class AuthenticationController {
    @Autowired
    UserService userService;

    @Transactional
    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    @ResponseBody
    public String authenticate(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        if (username.isEmpty() || username.length() > 64 ||
                password.isEmpty() || password.length() > 64)
            return Result.format(Result.PARAMETER_INVALID, "非法参数");

        try {
            User user = userService.findUserByUsername(username);
            if (user == null) {
                return Result.format(Result.USERNAME_NOT_EXISTS, "用户名不存在");
            }

            if (!user.getPassword().equals(password)) {
                return Result.format(Result.PASSWORD_INVALID, "密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }

        Date expiry = getExpiryDate(30 * 24 * 60); // 30 天有效时间

        String jwtString = JWTUtils.getAuthToken(username, expiry);

        Token token = new Token();
        token.setAuthToken(jwtString);
        token.setExpires(expiry);
        return Result.success(token);
    }

    @Transactional
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public String register(
            @RequestParam String username,
            @RequestParam String password) {
        if (username.isEmpty() || username.length() > 64 ||
                password.isEmpty() || password.length() > 64)
            return Result.format(Result.PARAMETER_INVALID, "非法参数");

        try {
            User user = userService.findUserByUsername(username);
            if (user != null) {
                return Result.format(Result.USERNAME_EXISTS, "用户名已经存在");
            }
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setNickname("user" + randomNickname(5));
            user.setAvatar("https://pic1.zhimg.com/da8e974dc_xl.jpg");
            userService.insert(user);
            return Result.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
    }

    private String randomNickname(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    private Date getExpiryDate(int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }
}
